package worktable

import (
	"os"
	"runtime"
	"gitee.com/xuesongtao/collect/library/collect"

	"github.com/gogf/gf/os/glog"
)

func AddLogPath() {
	collectProjects, err := collect.GetCollectProjects()
	if err != nil {
		glog.Error("GetCollectConfigs is failed, err:", err)
		return
	}

	for _, project := range collectProjects {
		if err := project.Valid(); err != nil {
			glog.Errorf("valid %q is no ok, err: %v", project.CfgFilename, err)
			continue
		}

		handler, err := project.GetPsHandle()
		if err != nil {
			glog.Error("project.GetPsHandle is failed, err:", err)
			continue
		}
		if err := plg.ReplacePath2Handler(project.GetLogFilename(), handler); err != nil {
			glog.Error("plg.ReplacePath2Handler is failed, err:", err)
		}
	}
	CronMonitor()
}

func AddLogDir() {
	collectProjects, err := collect.GetCollectProjects()
	if err != nil {
		glog.Error("GetCollectConfigs is failed, err:", err)
		return
	}

	for _, project := range collectProjects {
		if err := project.Valid(); err != nil {
			glog.Errorf("valid %q is no ok, err: %v", project.CfgFilename, err)
			continue
		}

		handler, err := project.GetPsHandle()
		if err != nil {
			glog.Error("project.GetPsHandle is failed, err:", err)
			continue
		}
		if err := plg.AddPath2Handler(project.GetLogDir(), handler); err != nil {
			glog.Error("plg.AddPath2Handler is failed, err:", err)
		}
	}
	CronMonitor()
}

// StartCollectWatch 开始执行监听
func StartCollectWatch() {
	AddLogDir()
	plg.CronLogs()
}

// CronMonitor 监控
func CronMonitor() {
	glog.Info(plg.List())
	printHeapInfo()
}

func printHeapInfo() {
	var m runtime.MemStats
	runtime.ReadMemStats(&m)
	glog.Infof("env:%v, heapsys:%d,heapalloc:%d,heapidel:%d,heapreleased:%d,heapinuse:%d",
		os.Getenv("GODEBUG"), m.HeapSys, m.HeapAlloc, m.HeapIdle, m.HeapReleased, m.HeapInuse)
}
